package no.kolstad.movies.editor;

import java.util.HashSet;
import java.util.Set;
import no.kolstad.movies.dao.RoleDAO;
import no.kolstad.movies.model.Role;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 *  Copyright [2008] Christopher Kolstad
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, software distributed under the License 
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License. 
 */

/**
 *
 * @author chriswk
 */
public class RoleEditor 
    extends java.beans.PropertyEditorSupport {
    
    protected Log log = LogFactory.getLog(this.getClass());
    
    RoleDAO rDao;
    
    public void setRoleDAO(RoleDAO dao) {
        this.rDao = dao;
    }
    
    /**
     * textValue is a comma separated list of role ids. Create a set
     * of Role objects.
     **/
    public void setAsText(String textValue) {
        Set<Role> roles = new HashSet<Role>();

        if (rDao == null) {
            if (log.isWarnEnabled()) {
                log.warn("Role DAO null");
            }
        } else {
            String[] ids = textValue.split(",");

            if (log.isDebugEnabled()) {
                log.debug(new ToStringBuilder(this)
                          .append("IDS")
                          .append(ids)
                          .toString());
            }

            for (int i = 0; i < ids.length; i++) {
                Role r = rDao.get(new Long(ids[i]));

                roles.add(r);
            }
        }

        setValue(roles);
    }

    /**
     * Must return null. If not - something calls toString and returns
     * the string representation of the Set to velocity - which then
     * can't iterate over it.
     **/
   public String getAsText() {
        return null;
    }
}
